package basesrv

import (
	"gorm.io/gorm"
	"interview/pkg/request"
)

// Paginate 计算分页需要的limit和offset
func Paginate(p *request.PageInfo) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		// 防止参数不合法
		pageNum, pageSize := p.PageNum, p.PageSize
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		if pageNum < 1 {
			pageNum = 1
		}
		p.PageNum, p.PageSize = pageNum, pageSize

		offset := (pageNum - 1) * pageSize
		return db.Offset(int(offset)).Limit(int(pageSize))
	}
}
